/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.common.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * List工具类
 *
 * @author yoara
 */
public class CommonListUtil {
	/**
	 * 创建ArrayList实例
	 * 
	 * @return ArrayList实例
	 */
	public static final <E> List<E> NEW() {
		return new ArrayList<>();
	}

	/**
	 * 创建ArrayList实例
	 * 
	 * @param initialCapacity 初始化容量
	 * @return ArrayList实例
	 */
	public static final <E> List<E> NEW(int initialCapacity) {
		return new ArrayList<>(initialCapacity);
	}

	/**
	 * 创建ArrayList实例
	 * 
	 * @param c 源集合
	 * @return ArrayList实例
	 */
	public static final <E> List<E> NEW(Collection<? extends E> c) {
		return new ArrayList<>(c);
	}

	/**
	 * 创建ArrayList实例
	 * 
	 * @param items 初始化元素列表
	 * @return ArrayList实例
	 */
	public static final <E> List<E> NEW(E... items) {
		List<E> list = NEW(items.length*2);
		Collections.addAll(list, items);
		return list;
	}

	/**
	 * 判断List是否为空(null||empty)
	 *
	 * @param list list
	 * @return boolean
	 */
	public static final boolean isEmpty(List<?> list) {
		return list == null || list.isEmpty();
	}

	/**
	 * 判断List是否为非空(null||empty)
	 *
	 * @param list list
	 * @return boolean
	 */
	public static final boolean isNotEmpty(List<?> list) {
		return !isEmpty(list);
	}

	/**
	 * 获取List的size
	 *
	 * @param list list
	 * @return int 为null时返回0
	 */
	public static final int size(List<?> list) {
		int size = 0;

		if (!isEmpty(list)) {
			size = list.size();
		}

		return size;
	}

	/**
	 * 将List转为字符串
	 *
	 * @param list list
	 * @param separtor 分隔符
	 * @return 字符串
	 */
	public static final String toString(List<?> list, String separtor) {
		StringBuilder sb = new StringBuilder();
		if (list != null && !list.isEmpty()) {
			sb.append(list.get(0));
			for (int i = 1; i < list.size(); i++) {
				sb.append(separtor).append(list.get(i));
			}
		}
		return sb.toString();
	}

	/**
	 * 将List转为字符串(分隔符:",")
	 *
	 * @param list list
	 * @return 字符串
	 */
	public static final String toString(List<?> list) {
		return toString(list, ",");
	}
}
